<?php

// 库房管理首页
class DepotAction extends Action
{
    public function _initialize()
    {
        checkLoginSession();
    }

    public function index()
    {

        $deptDao = D("Depot");
        $deptList = $deptDao->findAll();
        $this->assign('deptList', $deptList);
        
        $shelfDao = D("Shelf");
        $locDao = D("Location");
        
        $shelfList = $shelfDao->findAll();
        $locList = $locDao->findAll();  
              
        $this->assign('shelfList', $shelfList);
        $this->assign('locList', $locList);
       
        $this->display('Depot:index');
        
    }

    public function addDepot()
    {

        $dptDao = D("Depot");

        $data = array("depot_name" => $_GET["depot_name"], "depot_address" => $_GET["depot_address"],
            "depot_code" => strtoupper($_GET["depot_code"])); //默认编码大写
        if ($id_tb_depot = $dptDao->add($data))
        {
            $this->success('添加库房成功');
        }
        else
        {
            $this->success('添加库房失败');
        }

    }

    public function editDpt()
    {
        if (!empty($_GET['id_tb_depot']))
        {
            $Dpt = M("Depot");
            $vo = $Dpt->where('id_tb_depot=' . $_GET["id_tb_depot"])->find();
            if ($vo)
            {
                $this->assign('vo', $vo);
                $this->display();
            } else
            {
                exit('编辑项不存在！');
            }


        } else
        {
            exit('编辑项不存在！');
        }

    }

    public function updateDpt()
    {
        $Dpt = M("Depot");
        $data['depot_name'] = $_GET["depot_name"];
        $data['depot_code'] = $_GET["depot_code"];
        $data['depot_address'] = $_GET["depot_address"];
        if ($Dpt->where('id_tb_depot=' . $_GET["id_tb_depot"])->save($data))
            $this->success('数据修改成功！');
		else
		{
			exit('更新数据失败');
		}


    }

    public function optDepot()//修改库房开关状态的方法
    {

        $Dpt = M("Depot");
        $status = 'open';
        if ($_POST['status'] == 'open')
            $status = 'close';
        $did = $_POST['id_depot'];
        if ($result = $Dpt->where("id_tb_depot=" . $did)->setField('status', $status))            
        echo   ajaxrt('ok','修改状态成功');
         else
         {
         echo ajaxrt('error','修改状态出错');
         }   
    }


    public function addShlf()
    {
        $slfDao = D("Shelf");
        $locDao = D("Location");
        $data = array("id_tb_depot" => $_POST["id_tb_depot"], "depot_code" => $_POST["depot_code"],
            "shelf_layer" => $_POST["shelf_layer"], "shelf_num" => $_POST["shelf_num"],
            "describe" => $_POST["describe"], "date" => Date('Y-m-d'), "userid" => $_SESSION['UserInfo']['boss']);
        if ((strlen($_POST["shelf_num"]) > SHELF_CODE_LENGTH) or (strlen($_POST["shelf_layer"]) >
            SHELF_LAYER_CODE_LENGTH))
        {
           echo ajaxrt('error','货架数量或层数不符合要求');
        } 
        else
        {
            if ($id_tb_shelf = $slfDao->add($data))
            {
                $locs = makeLocs($_POST["depot_code"], $_POST["shelf_num"], $_POST["shelf_layer"]);
                if ($rtt = $locDao->execute($locs))
                {
                    echo ajaxrt('ok','货架记录和位置信息初始化成功');
                }
            }
            else
            {
                echo ajaxrt('error','添加货架记录失败');
            }
        }
    }

public function initLoc(){
    $slfDao = D("Shelf");    
    $locDao = D("Location");   
    $userid = $_SESSION['UserInfo']['boss'];
    $depot_code = $_POST["depot_code"];
    
    $locs = makeLocs($depot_code, $_POST["shelf_num"], $_POST["shelf_layer"]);
    if ($rtt = $locDao->execute($locs))
    {$upsql = "UPDATE `tb_shelf` SET `init` =  'true'  WHERE depot_code  = '$depot_code' and userid = '$userid'";
     if($rrt = $slfDao->execute($upsql))
     {echo ajaxrt('ok','货架记录和位置信息初始化成功');}
    }
    else
    {
    echo ajaxrt('error','初始化位置码失败');
    }    
}    

    public function In()
    {
        //$this->assign('content', 'Depot:In');
        $this->display('Depot:In');
    }

    public function addInRec()
    {               
        $inDptPdo = D("Depot_in");
        $in_fluNum = date('YmdGis');
        $userid = $_SESSION['UserInfo']['boss'];
        $data = array("in_fluNum" => $in_fluNum, "in_person" => $_SESSION['UserInfo']['user_name'],
            "count_person" => $_SESSION['count_person']['user_name'], "userid" =>$userid,
            "date" => date('Y-m-d'));
        $str = $_POST["data"];
        $datai = operInDetlRec($str);
        if( ($datai=='Error in Parseing InDepot data') OR ($datai=='Simple_code not exist') )//对客户端记录串处理
        {
            echo ajaxrt('error',$datai);
            EXIT();                            
        }   
        else
        {         
            if ($id_tb_depot_in = $inDptPdo->add($data))
            {   
                Session::set('nowInRec', $data);
                $inDptDetlPdo = D("Depot_in_detail");
    
                $x = count($datai);
                $y = 0;
                while ($y < $x)
                {
                    $datai[$y]['id_tb_depot_in'] = $id_tb_depot_in;
                    $datai[$y]['in_fluNum'] = $in_fluNum;
                    
                    if ($id_tb_depot_in_detail = $inDptDetlPdo->add($datai[$y]))
                    {
                        if (($rtrt = OperDpPtRec('jia', $datai[$y]['simple_code'], $datai[$y]['count'],$datai[$y]['location_code']))<1)
                        {echo ajaxrt('error','操作库存数据出错'); EXIT();}                       
                    }
                    else
                    {echo ajaxrt('error','写入详单数据出错');EXIT(); }
                    $y = $y + 1;
                }
                echo ajaxrt('ok','入库记录更新完毕',$_POST['data']); EXIT();   
            } else
            {
                Session::set('nowInRec', null);
                echo ajaxrt('error','写入库数据出错');EXIT(); 
            }
        } 

    }

    public function printInRec()
    {
        //$inRecFnum = '入库单流水号：'.date('YmdGis');
        $inRecFnum = '入库单流水号：' . $_SESSION['nowInRec']['in_fluNum'];
        Vendor('Tcpdf.tcpdf');
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('美工衣橱');
        $pdf->SetTitle('入库单');
        $pdf->SetSubject('流水号： ' . $inRecFnum);
        $pdf->SetKeywords('美工衣橱, 入库单');

        $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $inRecFnum,
            PDF_HEADER_STRING);
        $pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $pdf->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        $pdf->SetFont('droidsansfallback', '', 12);

        //$pdf->AddPage('B5');
        $pdf->AddPage();
        $str = $_GET["data"];
        $htmlstr = '<table><tr><td>商品编码</td><td>商品数量</td><td>货架编码</td></tr>';
        $line = '';
        $tok = strtok($str, " @-");
        $i = 0;
        //var arrayIn = new Array();

        while ($tok !== false)
        {
            $i++;
            switch (($i % 3))
            {
                case 1:
                    $line = $line . '<tr><td>' . $tok . '</td>';
                    break;
                case 2:
                    $line = $line . '<td>' . $tok . '</td>';
                    break;
                case 0:
                    $line = $line . '<td>' . $tok . '</td></tr>';
                    break;
                default:
                    echo "Error in Parseing InDepot data";
            }

            $tok = strtok("@-");
        }
        $htmlstr = $htmlstr . $line . '</table>';
        $sign = '<br/>入库人签名: ' . $_SESSION['nowInRec']['in_person'] . '<br/>清点人签名：' . $_SESSION['nowInRec']['count_person'] .
            '<br/>本次商品所属商家：' . $_SESSION['nowInRec']['userid'] . '<br/>' . date('Y年m月d日');
        //..     ';
        $htmlstr = $htmlstr . $sign;

        $pdf->writeHTML($htmlstr, true, false, true, false, '');
        $pdf->Output('inDepotReceipt.pdf', 'I');
    }


    public function showOrdDetl()
    {

        $ordDetalDao = D("Order_detail");
        $tname = 'Order_detail';
        $Field = 'id_tb_Order_detail';
        $Asc = ' ASC';

        $searchwords = 'id_tb_order = ' . $_POST['id_tb_order'];
        $arrayVa = ShowTable($tname, $Field, $Asc, $searchwords);
        $ordDetalList = $arrayVa['a'];
        $page = $arrayVa['b'];
        if (count($arrayVa['a']) < 1 or ($arrayVa['a'] == null))
        {
            $this->assign('empty', '没有记录');
        }
        echo ajaxrt('ok','获得详单数据成功',$ordDetalList);
    }
    
    public function getPrdD()//查询界面，根据简码获得商品信息并ajax返回
    {
        $spcode = $_POST['simple_code'];
        if (isset($_POST['count']))
        {
            $count = $_POST['count'];
        } else
        {
            $count = 0;
        }
		$userid = $_SESSION['UserInfo']['boss'];
        $where = 'simple_code = ' . "'" . $spcode . "'" . ' and count >= ' . $count ."  and userid = '$userid'";
        $Detal = D('Product_all_info');
        $recs = $Detal->where($where)->findAll();        
        echo ajaxrt('ok','获取详细商品信息成功',$recs);
    }


    public function getDetailRec()//根据流水号获得详单数据并返回
    {

        $Detal = D('Depot_in_detail');
        $dpin_id = $_POST['dpdt_id'];
		$userid = $_SESSION['UserInfo']['boss'];
        $recs = $Detal->where('id_tb_depot_in = ' . $dpin_id)->findAll();
        $ct = count($recs);
        if ($ct < 1)
        {
         echo ajaxrt('error','该入库记录不存在详单');
        } else
        {
        echo ajaxrt('ok','成功获得详单数据',$recs);
        }
    }
    
    public function _outme()
    { 
      $orderid = $_POST['orderid'];
	  $sn = $_POST['sn'];
      $note = $_POST['note'];
      $exp_number = $_POST['exp_number'];
      $userid = $_SESSION['UserInfo']['boss'];
      $conduct_id = $_SESSION['UserInfo']['user_id'];
      $ordPDO = D('Order');      
      $DptPDO = D('Depot_product');
      $orddtlPDO = D('Order_detail');
      $lccPdo = D('Loc_code_count');
	  $stanow= 'Delivering';
	 if(OrderLog('Pre',$stanow,$note,$orderid,$sn,$userid,$conduct_id))
      {
            if($rt2 = $ordPDO->execute("UPDATE `tb_order` SET `status` =  'Delivering' ,`exp_number` ='$exp_number'  WHERE serial_number = '$sn' and userid = '$userid'"))
            {
                $i=0;$j=0;
                $rtrt =$orddtlPDO->where('serial_number = ' . "'" .$sn . "'" ." and id_tb_order  = '$orderid'")->findAll();
                $rtt = count($rtrt);
                if($rtt<1)
                {
                  echo ajaxrt('error','订单的详单记录为空');  
                }
                else//遍历订单详单
                {   
                    while($i<$rtt)//把详单里面的每条记录编码对应的库存商品库存实际出库
                    {   //默认是出库时库存记录dp一定能满足订单出库需要
                        $ctt = $rtrt[$i]['count'];//某详单的数量
                        $spcode = $rtrt[$i]['simple_code'];//某详单的简码
                        
                        //简码存放的位置码记录集合
						$lccrt = $lccPdo->where("  simple_code = '$spcode' "." and  userid = '$userid'")->findAll();
                        
                        $updpsqlstr = "UPDATE `tb_depot_product` SET `real_count` =real_count - $ctt,
                            `lock_sale_count` = lock_sale_count - $ctt where  simple_code = '$spcode' and userid = '$userid'";
                            
                        $DptPDO->execute($updpsqlstr);
                        
                        $uplccsqlstr = "UPDATE `tb_loc_code_count` SET `count` =count - $ctt
                            where  simple_code = '$spcode'  and  userid = '$userid'";
                             
                        $k = count($lccrt)-1;                       
						while(($k>0) and ($ctt>0))//lcc表存在多条简码的存储记录（多个位置）
						{ 
                            $idd = $lccrt[$k]['id_tb_loc_code_count'];
                            $dellccsqlstr = "DELETE FROM `tb_loc_code_count` 
                                WHERE `id_tb_loc_code_count` = $idd LIMIT 1";
                            
							if($lccrt[$k]['count'] > $ctt)//该条数量大于订单数量
							{
                            $lccPdo->execute($uplccsqlstr);   $ctt =0;                     							
							}							
							else if($lccrt[$k]['count'] == $ctt)
							{
							 $lccPdo->execute($dellccsqlstr);  $ctt =0;                                                     
                            }

							else if($lccrt[$k]['count'] < $ctt)
							{
                            $ctt = $ctt - $lccrt[$k]['count'];
                            $lccPdo->execute($dellccsqlstr);  
							}
						}
						//
                        $i = $i +1;                
                    }
                    echo  ajaxrt('ok','完成啦');                                    
                }
            }  
            else
            {
            echo ajaxrt('error','更新订单表出错');
            }                   
      }
      else
      {
        echo ajaxrt('error','更新订单log表出错');
      }
    }
    
    public function ifexitCt(){//添加下单记录验证编码和数量操作
          if(isset($_POST['c']) AND isset($_POST['s'])){
                $spcode = $_POST['s'];
                $userid = $_SESSION['UserInfo']['boss'];
              //$ct = exitcount($_POST['s'],$_POST['c']);
              $dpPDO = D('Depot_product');
            $rt = $dpPDO->where('simple_code = '."'".$spcode."'".' and userid = '."'$userid'")->find();			
            if(count($rt) >0 )
            {	$ct=$rt['real_count'] - $rt['lock_sale_count'];
				if($ct>$_POST['c']) echo ajaxrt('ok','编码和数量都存在');
				else
				echo ajaxrt('error','请求数量大于当前库存:'.$ct); 
            }
            else
            {
                echo ajaxrt('error','编码不存在');    
            } 
        }      
    }  
}

?>